/**
 * base64解码
 * @param {string} str str
 * @param {string}
 */
export function encodeBase64(str) {
	return new Buffer.from(str).toString('base64');
}

/**
 * base64解码
 * @param {string} str str
 * @param {string}
 */
export function decodeBase64(str) {
	const commonContent = str.replace(/\s/g, '+');
	return new Buffer.from(commonContent, 'base64').toString();
}

/**
 * 图片转base64
 * @param {string} src 图片地址
 * @return {Promise} base64
 */
export function imageToBase64(src) {
	return new Promise((resolve, reject) => {
		// #ifdef MP-WEIXIN
		uni.getImageInfo({
			src,
			success: image => {
				console.log(image);
				uni.getFileSystemManager().readFile({
					filePath: image.path,
					encoding: 'base64',
					success: e => {
						return resolve(`data:image/jpeg;base64,${e.data}`);
					},
					fail: e => {
						return reject(null);
					}
				})
			}
		});
		// #endif

		// #ifdef H5
		uni.request({
			url: src,
			method: 'GET',
			responseType: 'arraybuffer',
			success: res => {
				let base64 = uni.arrayBufferToBase64(res.data); //把arraybuffer转成base64
				base64 = 'data:image/jpeg;base64,' + base64;
				return resolve(base64);
			},
			fail: (e) => {
				console.log("图片转换失败");
				return reject(null);
			}
		})
		// #endif
	})
}


/*
 *处理数据分类方法
 */

export function DataReduce(arr, property) {
	return new Promise((resolve, reject) => {
		if (!Array.isArray(arr)) return resolve([]);
		let Arr = arr.reduce((pre, obj) => {
			let quyu_ = obj[property] == '永春现代生物医药城' ? '朝阳区' : obj[property]
			var newObj = {
				[property]: quyu_,
				data: [obj],
			};
			if (!pre.length) {
				return [newObj];
			}
			for (let i = 0; i < pre.length; i++) {
				let item = pre[i];
				if (item[property] === quyu_) {
					item.data = [...item.data, obj];
					return pre;
				}
			}
			return [...pre, newObj];
		}, []);
		return resolve(Arr)
	})
}